//
//  SEGPublishHelpViewModel.m
//  Commom
//
//  Created by 梁学彰 on 2020/6/10.
//

#import "SEGPublishHelpViewModel.h"
#import "SEGCommunitySocialManager.h"

@implementation SEGPublishHelpViewModel
#pragma mark - life cycle


#pragma mark - init
- (void)initData {
    SEGProfileModel *sysAccount = [SEGProfileManager sharedManager].profile;
    NSString* nickName = sysAccount.nickname;
    if ([nickName length] == 0) {
        nickName = sysAccount.tel;
    }
    if (self.type == SEGPublishHelpType_AttendTopic) {
        // 园区：直接显示项目名，非园区：显示城市+名称
        NSString *communityName = [NSString stringWithFormat:@"来自%@ %@", sysAccount.city, sysAccount.communityName];
        
        //把数据保存在字典中，进行传输
        self.saveDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[self.tempDict valueForKey:@"objId"], @"objId",
                         @"5", @"objType",
                         @"内容", @"quizContent",
                         kAccountUserID, @"userId",
                         [self.tempDict valueForKey:@"quizTypeId"], @"quizTypeId",
                         @"3", @"quizRangeId",
                         ValueToString(sysAccount.cityId), @"regionId", //城市编码
                         ValueToString(sysAccount.jobCommunity), @"organId", //小区id
                         [self.tempDict valueForKey:@"linkTitle"], @"linkTitle",
                         @"", @"quizPic", //图片拼接
                         communityName, @"communityName", //城市+名称
                         //nickName, @"creator",
                         [self.tempDict valueForKey:@"linkUrl"], @"linkUrl", nil];
    }else {
        
        NSString *quizTypeId = [self.tempDict valueForKey:@"id"];
        if (!quizTypeId) {
            if (self.type == SEGPublishHelpType_Help) {
                quizTypeId = @"10002";
            }else {
                quizTypeId = @"14";//线上其他类型的id
            }
        }
        
        // 园区：直接显示项目名，非园区：显示城市+名称
        NSString *communityName = [NSString stringWithFormat:@"来自%@ %@", sysAccount.city, sysAccount.communityName];
        
        //把数据保存在字典中，进行传输
        self.saveDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"", @"objId",
                         @"2", @"objType",
                         @"内容", @"quizContent",
                         sysAccount.userId, @"userId",
                         quizTypeId, @"quizTypeId",
                         @"3", @"quizRangeId",
                         sysAccount.cityId, @"regionId", //城市编码
                         sysAccount.jobCommunity, @"organId", //小区id
                         @"", @"linkUrl",
                         @"", @"linkTitle",
                         @"", @"quizPic", //图片拼接
                         communityName, @"communityName", //城市+名称
                         nickName, @"creator", nil];
        
        if (self.type == SEGPublishHelpType_Help) {//帮帮@"1", @"isBroadCast",
            [self.saveDict setObject:@"1" forKey:@"isBroadCast"];
        }
    }
    
    self.hasSubmit = NO;
    self.savePicArray = [[NSMutableArray alloc] init];
    self.saveUrlArray = [[NSMutableArray alloc] init];
}

#pragma mark - send request
- (RACSignal *)submitRequest {
    return [RACSignal concat:@[[self checkSubmitParams],[self upLoadImageRequest],[self sendRequest]]];
}

- (RACSignal *)upLoadImageRequest {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        self.hasSubmit = YES;
        [subscriber sendNext:@(1)];
        //只上传没有url的图片，也就是新增图片
        NSArray *uploadArr = [self.savePicArray subarrayWithRange:NSMakeRange(self.saveUrlArray.count, self.savePicArray.count - self.saveUrlArray.count)];
        if(uploadArr.count > 0) {
            [[SEGMultipartfileuploadManager sharedManager] requestMultipartfileuploadWithImage:uploadArr progress:nil completed:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if(isSuccessed) {
                    NSArray *data = result[@"data"];
                    //存储图片链接
                    [self.saveUrlArray addObjectsFromArray:data];
                    [subscriber sendCompleted];
                }else {
                    self.hasSubmit = NO;
                    [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:300 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                    return ;
                }
            }];
        }else {
            [subscriber sendCompleted];
        }
        
        return nil;
    }];
    return signal;
}

/// 请求发布
- (RACSignal *)sendRequest {
    
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        NSString *quizContent;
        if (self.type == SEGPublishHelpType_AttendTopic) {
            quizContent = [self.describeViewString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"#%@#", [self.tempDict valueForKey:@"linkTitle"]] withString:@""];
        }else {
            quizContent = self.describeViewString;
        }
        if (!quizContent) {
            quizContent = @"";
        }
        quizContent = [quizContent stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        [self.saveDict setValue:quizContent forKey:@"quizContent"];
        NSString* urlString = [self.saveUrlArray componentsJoinedByString:@","];
        [self.saveDict setValue:urlString forKey:@"quizPic"];
        [self.saveDict setValue:[SEGProfileManager sharedManager].profile.jobCommunity forKey:@"communityId"];

        SEGCommunitySocialManager *manager = [[SEGCommunitySocialManager alloc] init];
        
        [manager requestSaveQuizWithParams:self.saveDict Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
            
            if (isSuccessed) {
                if (self.type == SEGPublishHelpType_AttendTopic) {
                    //话题发帖积分行为设置
                    [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.topic module:SEGIntegralModule.topicDetail businessID:ValueToString(self.saveDict[@"objId"]) finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    }];
                    // 刷新话题列表
                    [[NSNotificationCenter defaultCenter] postNotificationName:SEGAttendTopicFinishedNotification object:nil];
                }else {
                    //帮帮发帖积分行为设置
                    [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.postForHelp module:SEGIntegralModule.neighborhoodCircle businessID:nil finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    }];
                    //刷新帮帮
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"SEGHelpDeatilViewControllerNotification" object:nil];
                    // 刷新邻里圈
                    [[NSNotificationCenter defaultCenter] postNotificationName:SEGPublishGoodsFinishedNotification object:nil];
                }
                self.hasSubmit = NO;
                [subscriber sendCompleted];
            }else {
                self.hasSubmit = NO;
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:codeType.integerValue userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
            }
        }];
        
        return nil;
    }];
    return signal;
    
    
}

#pragma mark - custom delegate

#pragma mark - system delegate

#pragma mark - event response

#pragma mark - private methods
- (RACSignal *)checkSubmitParams {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        if (self.hasSubmit) {
            self.hasSubmit = NO;
            [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@""}]];
            return nil;
            //失败了 返回
        }

        //检查参数填写
        NSString *quizContent;
        if (self.type == SEGPublishHelpType_AttendTopic) {
            quizContent = [self.describeViewString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"#%@#", [self.tempDict valueForKey:@"linkTitle"]] withString:@""];
        }else {
            quizContent = self.describeViewString;
        }
        
        if (self.type == SEGPublishHelpType_AttendTopic) {
            if ([[self.tempDict valueForKey:@"imageType"] boolValue]) {//图文话题可以没有文字，一定要有图
                if (!self.savePicArray.count) {
                    self.hasSubmit = NO;
                    [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:200 userInfo:@{NSLocalizedDescriptionKey:@"请上传图片"}]];
                    return nil;
                }
            }
            if (quizContent.length > 70) {
                self.hasSubmit = NO;
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:200 userInfo:@{NSLocalizedDescriptionKey:@"亲，您输入的内容已超过70字。"}]];
                return nil;
            }
        } else {
            NSString *fillterQuizContent = [quizContent stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            if (fillterQuizContent.length < 5) {
                self.hasSubmit = NO;
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:200 userInfo:@{NSLocalizedDescriptionKey:@"输入内容不能少于5个字。"}]];
                return nil;
            }else if (fillterQuizContent.length > kPostCommentMaxLength){
                self.hasSubmit = NO;
                NSString *errorMessage = [NSString stringWithFormat:@"亲，您输入的内容已超过%ld字。", kPostCommentMaxLength];
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:200 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                return nil;
            }
        }

        
        [subscriber sendCompleted];
        return nil;
    }];
    return signal;
}
#pragma mark - setter and getter

@end
